'use strict'

const Controller = require('egg').Controller

const UserBoundDeviceModel = require('../../models/user_bound_device')

const EquipmentModel = require('../../models/equipment')

class UserDeviceController extends Controller {
  userBoundDeviceModel = UserBoundDeviceModel(this.app.model)

  equipmentModel = EquipmentModel(this.app.model)

  async query() {
    const { ctx } = this
    try {
      const user_id = ctx.userId
      const where = { del_flag: '0', user_id };
      if (!user_id) {
        return ctx.failure('当前token无法查询到关联信息', error)
      }
      const result = await this.userBoundDeviceModel.findAll({ where })
      const _result = await Promise.all(
        result.map(async item => {
          const equipment_id = item?.dataValues?.equipment_id
          const deviceResult = await this.equipmentModel.findOne({
            where: { id: equipment_id },
          })
          return { ...item.dataValues, name: deviceResult?.name || 'Unknown', imei: deviceResult?.equipment_id }
        })
      )
      ctx.success('查询成功', _result)
    } catch (error) {
      ctx.failure('查询失败', error)
    }
  }

  async delete() {
    const { ctx } = this
    try {
      const user_id = ctx?.userId
      if (!user_id) {
        return ctx.failure('用户ID为空', error)
      }
      const where = { user_id }
      const result = await this.userBoundDeviceModel.update(
        { del_flag: '1' },
        { where }
      )
      ctx.success('解绑成功', result)
    } catch (error) {
      ctx.failure('解绑失败', error)
    }
  }
}

module.exports = UserDeviceController
